<template>
  <tr>
    <!-- 使用正确的计算属性 -->
    <td>{{ currentStudentInfo.name }}</td>
    <td>
      Class {{ currentStudentInfo.class }} | Grade
      {{ currentStudentInfo.grade }}
    </td>
    <td>{{ scoreItem.subject }}</td>
    <td>{{ scoreItem.semester_year }} {{ scoreItem.semester_season }}</td>
    <td>{{ scoreItem.score }}</td>
    <th>
      <button
        class="btn btn-ghost btn-sm"
        @click="
          router.push({ name: 'score-edit', params: { id: scoreItem.id } })
        "
      >
        details
      </button>
      <button class="btn btn-error btn-sm">delete</button>
    </th>
  </tr>
</template>

<script setup>
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user";
import { getStuentByStuentId } from "@/services/ApiStudent";
import { getUserId } from "@/ultils/tokenHelper";
import { storeToRefs } from "pinia";
import { ref, computed, onMounted } from "vue";

// 从props中解构出scoreItem和currentStudent
const props = defineProps({ scoreItem: Object, currentStudent: Object });
const { scoreItem, currentStudent } = props;

const userStore = useUserStore();
const { isStudent } = storeToRefs(userStore);
const router = useRouter();

// 定义响应式数据存储学生信息
const studentInfo = ref({ name: "keyi", class: "8", grade: "10" });

// 定义计算属性来获取学生信息
const currentStudentInfo = computed(() => {
  if (isStudent.value) {
    return studentInfo.value;
  } else {
    return currentStudent || studentInfo.value;
  }
});

// 在onMounted中处理异步数据获取
onMounted(async () => {
  if (isStudent.value) {
    const userId = getUserId();
    try {
      const student = await getStuentByStuentId(userId);
      if (student && student[0]) {
        studentInfo.value = student[0];
      }
    } catch (error) {
      console.error("获取学生信息失败:", error);
    }
  } else if (currentStudent) {
    // 老师视角下，使用props传入的currentStudent
    studentInfo.value = currentStudent;
  }
});
</script>
